<?php

namespace app\admin\controller\kuyou;

use app\common\controller\Backend;
use think\Db;
use Exception;
use think\Session;

/**
 * 销货订单
 *
 * @icon fa fa-circle-o
 */
class GoodsSalesOrder extends Backend
{
    protected $noNeedRight = ['getReceivingAddress', 'checkPurchase'];

    /**
     * GoodsSalesOrder模型对象
     * @var \app\admin\model\kuyou\GoodsSalesOrder
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $setData = (new Goods())->getSetData();
        $this->assign('set', $setData['setList']);
        $this->assignconfig('set', $setData['setList']);
        $this->assign('nowmenu', $setData['nowmenu']);

        $this->model = new \app\admin\model\kuyou\GoodsSalesOrder;
        $this->view->assign("purchaseTypeList", $this->model->getPurchaseTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("checkStatusList", $this->model->getCheckStatusList());
        $this->view->assign("examineStatusList", $this->model->getExamineStatusList());

        $this->view->assign("suppliersList", $this->model->getSuppliersList($this->shop_id));
        $this->view->assign("storesList", $this->model->getStoresList($this->shop_id));
        $this->assignconfig("storesList", $this->model->getStoresList($this->shop_id));

        $this->view->assign("goodsList", $this->model->getGoodsList($this->shop_id));
        $this->assignconfig("goodsList", $this->model->getGoodsList($this->shop_id));

        $this->view->assign("adminList", $this->model->getAdminList($this->shop_id));
        $this->view->assign("accountsList", $this->model->getAccountsList($this->shop_id));

        $this->view->assign("customers", $this->model->getCustomersList($this->shop_id));
        $this->view->assign("saleList", $this->model->getSaleList($this->shop_id));
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $sort = 'purchase_time';
            $order = 'DESC';
            $list = $this->model
                ->with(['customers', 'preparation', 'examine'])
                ->where('goods_sales_order.shop_id', $this->shop_id)
                ->where($where)
                ->order($sort, $order)
                ->order('purchase_code', 'DESC')
                ->paginate($limit);

            foreach ($list as $row) {
                $row->getRelation('customers')->visible(['customer_name']);
                $row->getRelation('preparation')->visible(['username']);
                $row->getRelation('examine')->visible(['username']);
            }
            foreach ($list as $list_k => $list_v) {
                if (isset($list_v['print_num']) && empty($list_v['print_num'])) {
                    $list[$list_k]['print_num'] = 0;
                }
                $purchase_id = Db::name('kuyou_goods_saleord')->where('shop_id', $this->shop_id)->where(['order_id' => $list_v['id']])->column('purchase_id');
                $purchase = Db::name('kuyou_goods_sales')->where('shop_id', $this->shop_id)->where(['id' => ['in', $purchase_id]])->column('purchase_code');
                $list[$list_k]['purchase_id'] = implode(',', $purchase);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
            if ($params) {
                (new \app\admin\controller\kuyou\Checkout())->checkOutTime($params['purchase_time']);
                if (empty($params['customers_id'])) {
                    $this->error('请选择客户');
                }
                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if (!isset($status)) {
                    $this->error('请填写详情数据');
                }
                $params = $this->preExcludeFields($params);
                $admin = Session::get('admin');

                if (empty($params['purchase_code'])) {
                    $this->error('请填写单据编号');
                }

                if (empty($params['customers_id'])) {
                    $this->error('请选择客户');
                }
                $customers = Db::name('kuyou_customers')->where('shop_id', $this->shop_id)->where(['id' => $params['customers_id']])->find();
                if (empty($customers)) {
                    $this->error('客户不存在');
                }

                $data = [];
                $number = 0;
                $all_money = 0;
                $tax_money = 0;
                $money_tax_price = 0;
                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $number += $params['number'][$k];
                        $all_money += $params['all_money'][$k];
                        $tax_money += (float)$params['tax_money'][$k];
                        $money_tax_price += (float)$params['money_tax_price'][$k];
                        if (!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])) {
                            $this->error('请选择仓库');
                        }

                        $goods = Db::name('kuyou_goods')->where('shop_id', $this->shop_id)->where(['goods_code' => $v])->find();
                        if (empty($goods)) {
                            $this->error('商品不存在');
                        } elseif ($goods['auxiliary'] == 1 && empty($params['goods_attr'][$k])) {
                            $this->error('请选择商品属性');
                        }

                        $data[] = [
                            'shop_id' => $this->shop_id,
                            'purchase_code' => $params['purchase_code'],
                            'purchase_type' => $params['purchase_type'],
                            'purchase_time' => strtotime($params['purchase_time']),
                            'delivery_time' => strtotime($params['delivery_time']),
                            'customers_id' => (int)$params['customers_id'],//客户
                            'sale_user' => (int)$params['sale_user'],//销售员
                            'receiving_address' => $params['receiving_address'],

                            'goods_code' => $v,//商品信息
                            'goods_note' => $params['goods_note'][$k],
                            'goods_unit' => (int)$params['goods_unit'][$k],

                            'stores_id' => (int)$params['stores_id'][$k],
                            'allow_stock' => (float)$params['allow_stock'][$k],
                            'number' => (float)$params['number'][$k],
                            'purchase_number' => (float)$params['number'][$k],
                            'default_unit' => (float)$params['default_unit'][$k],
                            'basic_nmber' => (float)$params['basic_nmber'][$k],
                            'unit_price' => (float)$params['unit_price'][$k],
                            'cost_price' => (new Goods())->getCost_Price($v, $params['stores_id'][$k]),
                            'discount' => (float)$params['discount'][$k],
                            'dis_money' => (float)$params['dis_money'][$k],
                            'all_money' => (float)$params['all_money'][$k],
                            'remark' => $params['remark'][$k],

                            'preferential_rate' => (float)$params['preferential_rate'],
                            'preferential_money' => (float)$params['preferential_money'],
                            'real_money' => (float)$params['real_money'],

                            'goods_attr' => (float)$params['goods_attr'][$k],
                            'tax_included' => (float)$params['tax_included'][$k],
                            'tax_rate' => (float)$params['tax_rate'][$k],
                            'tax_money' => (float)$params['tax_money'][$k],
                            'money_tax_price' => (float)$params['money_tax_price'][$k],

                            'preparation_id' => $admin['id'],
                            'operation_id' => $admin['id'],

                            'library_number' => (float)$params['number'][$k],
                            'library_money' => (float)$params['all_money'][$k],

                            'createtime' => time(),
                            'updatetime' => time(),
                        ];
                    }
                }
                if (!empty($data)) {
                    $row = [
                        'shop_id' => $this->shop_id,
                        'purchase_code' => $params['purchase_code'],
                        'purchase_type' => $params['purchase_type'],
                        'purchase_time' => strtotime($params['purchase_time']),
                        'delivery_time' => strtotime($params['delivery_time']),
                        'customers_id' => (int)$params['customers_id'],//客户
                        'sale_user' => (int)$params['sale_user'],//销售员
                        'receiving_address' => $params['receiving_address'],
                        'number' => $number,
                        'all_money' => $all_money,

                        'tax_money' => $tax_money,
                        'money_tax_price' => $money_tax_price,

                        'preferential_rate' => (float)$params['preferential_rate'],
                        'preferential_money' => (float)$params['preferential_money'],
                        'real_money' => (float)$params['real_money'],
                        'note' => $params['note'],
                        'preparation_id' => $admin['id'],
                        'operation_id' => $admin['id'],
                        'createtime' => time(),
                        'updatetime' => time(),
                    ];
                }

                if ($this->model->where('shop_id', $this->shop_id)->where(['purchase_code' => trim($params['purchase_code'])])->find()) {
                    $this->error('单据编号已占用');
                }

                //附件记录开始
                $enclosureLog = [];
                if (isset($params['enclosure']) && !empty($params['enclosure'])) {//选择了原始单据
                    $enclosure = explode(',', $params['enclosure']);
                    $enclosurelist = Db::name('kuyou_enclosure')->where('shop_id', $this->shop_id)->where(['id' => ['in', $params['enclosure']]])->select();
                    if (sizeof($enclosurelist) != sizeof($enclosure)) {
                        $this->error('选择的原始单据有误，请重新选择');
                    } else {
                        foreach ($enclosure as $k => $v) {
                            $enclosureLog[] = [
                                'shop_id' => $this->shop_id,
                                'enclosure_id' => $v,
                                'purchase_code' => $params['purchase_code'],
                                'type' => '4',
                            ];
                        }
                    }
                    unset($params['enclosure']);
                }
                //附件记录结束

                $result = false;
                Db::startTrans();
                try {
                    if (!empty($row)) {
                        $result = $this->model->insertGetId($row);
                    }

                    //添加附件记录
                    if (!empty($enclosureLog)) {
                        foreach ($enclosureLog as $enclosureLog_k => $enclosureLog_v) {
                            $enclosureLog[$enclosureLog_k]['order_id'] = $result;
                        }
                        Db::name('kuyou_enclosure_log')->insertAll($enclosureLog);
                    }
                    //添加附件记录结束

                    Db::name('kuyou_goods_sales_order_info')->where('shop_id', $this->shop_id)->where(['purchase_code' => $params['purchase_code']])->delete();
                    Db::name('kuyou_goods_sales_order_info')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if (isset($result) && $result !== false) {
                    if ($examine != 1) {
                        try {
                            $exa = $this->examine($result, 1);
                        } catch (Exception $e) {
                        }
                        if (!isset($exa) || $exa['status'] != 1) {
                            $exa = $this->examine($result, 1);
                            try {
                                $this->del($result);
                            } catch (Exception $e) {
                            }
                            $this->error($exa['msg']);
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $code = (new Goods())->getCodes('', 10);
        $this->view->assign("code", $code);

        $last_customer = \think\Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'customer'])->value('is_checked');
        $set_customer = '';
        if ($last_customer) {
            $set_customer = Db::name('kuyou_goods_sales_order')->where('shop_id', $this->shop_id)->where((new Goods())->setWhere())->order('id', 'DESC')->value('customers_id');
        }
        $this->view->assign("set_customer", $set_customer);
        $address = Db::name('kuyou_customers')->where('shop_id', $this->shop_id)->where((new Goods())->setWhere(['id' => $set_customer]))->value('getgoods_address');
        $this->view->assign("address", $address);

        $last_read = \think\Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'last_read'])->value('is_checked');
        $sale_user = '';
        if ($last_read) {
            $sale_user = Db::name('kuyou_goods_sales_order')->where('shop_id', $this->shop_id)->where((new Goods())->setWhere())->order('id', 'DESC')->value('sale_user');
        }
        $this->view->assign("sale_user", $sale_user);

        $kuyou_customers = Db::name('kuyou_customers')->where('shop_id', $this->shop_id)->where(['id' => $set_customer])->field('id,customer_name')->find();
        $this->assignconfig("kuyou_customers", $kuyou_customers);
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            (new \app\admin\controller\kuyou\Checkout())->checkOutTime($row['purchase_time']);
            $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
            if ($row['examine_status'] == 1 && $examine == 1) {
                $this->error('不能编辑已审核的数据');
            }
            if ($row['purchase_type'] == 1) {
                $purchase_id = Db::name('kuyou_goods_saleord')->where('shop_id', $this->shop_id)->where(['order_id' => $ids])->column('purchase_id');
                if (!empty($purchase_id)) {
                    $this->error('不能编辑已生成销货单的数据');
                }
            } else {
                $purchase_id = Db::name('kuyou_goods_saleexc')->where('shop_id', $this->shop_id)->where(['purchase_id' => $ids])->column('exchange_id');
                if (!empty($purchase_id)) {
                    $this->error('不能编辑已生成退货单的数据');
                }
            }

            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if (empty($params['customers_id'])) {
                    $this->error('请选择客户');
                }
                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $status = true;
                    }
                }
                if (!isset($status)) {
                    $this->error('请填写详情数据');
                }
                if (empty($params['purchase_code'])) {
                    $this->error('请填写单据编号');
                }

                if (empty($params['customers_id'])) {
                    $this->error('请选择客户');
                }
                $customers = Db::name('kuyou_customers')->where('shop_id', $this->shop_id)->where(['id' => $params['customers_id']])->find();
                if (empty($customers)) {
                    $this->error('客户不存在');
                }

                $admin = Session::get('admin');

                $data = [];
                $number = 0;
                $all_money = 0;
                $tax_money = 0;
                $money_tax_price = 0;
                foreach ($params['goods_code'] as $k => $v) {
                    if (!empty($v)) {//有产品编号
                        $number += $params['number'][$k];
                        $all_money += $params['all_money'][$k];
                        $tax_money += (float)$params['tax_money'][$k];
                        $money_tax_price += (float)$params['money_tax_price'][$k];

                        if (!isset($params['stores_id'][$k]) || empty($params['stores_id'][$k])) {
                            $this->error('请选择仓库');
                        }

                        $goods = Db::name('kuyou_goods')->where('shop_id', $this->shop_id)->where(['goods_code' => $v])->find();
                        if (empty($goods)) {
                            $this->error('商品不存在');
                        } elseif ($goods['auxiliary'] == 1 && empty($params['goods_attr'][$k])) {
                            $this->error('请选择商品属性');
                        }

                        $data[] = [
                            'shop_id' => $this->shop_id,
                            'purchase_code' => $params['purchase_code'],
                            'purchase_type' => $params['purchase_type'],
                            'purchase_time' => strtotime($params['purchase_time']),
                            'delivery_time' => strtotime($params['delivery_time']),
                            'customers_id' => (int)$params['customers_id'],//客户
                            'sale_user' => (int)$params['sale_user'],//销售员
                            'receiving_address' => $params['receiving_address'],

                            'goods_code' => $v,//商品信息
                            'goods_note' => $params['goods_note'][$k],
                            'goods_unit' => (float)$params['goods_unit'][$k],

                            'stores_id' => (float)$params['stores_id'][$k],
                            'allow_stock' => (float)$params['allow_stock'][$k],
                            'number' => (float)$params['number'][$k],
                            'purchase_number' => (float)$params['number'][$k],
                            'default_unit' => (float)$params['default_unit'][$k],
                            'basic_nmber' => (float)$params['basic_nmber'][$k],
                            'unit_price' => (float)$params['unit_price'][$k],
                            'cost_price' => (new Goods())->getCost_Price($v, $params['stores_id'][$k]),
                            'discount' => (float)$params['discount'][$k],
                            'dis_money' => (float)$params['dis_money'][$k],
                            'all_money' => (float)$params['all_money'][$k],
                            'remark' => $params['remark'][$k],

                            'preferential_rate' => (float)$params['preferential_rate'],
                            'preferential_money' => (float)$params['preferential_money'],
                            'real_money' => (float)$params['real_money'],

                            'goods_attr' => (float)$params['goods_attr'][$k],
                            'tax_included' => (float)$params['tax_included'][$k],
                            'tax_rate' => (float)$params['tax_rate'][$k],
                            'tax_money' => (float)$params['tax_money'][$k],
                            'money_tax_price' => (float)$params['money_tax_price'][$k],

                            'library_number' => (float)$params['number'][$k],
                            'library_money' => (float)$params['all_money'][$k],

                            'preparation_id' => $admin['id'],
                            'operation_id' => $admin['id'],
                            'createtime' => $row['createtime'],
                            'updatetime' => time(),
                        ];
                    }
                }
                if (!empty($data)) {
                    $rowdata = [
                        'shop_id' => $this->shop_id,
                        'purchase_code' => $params['purchase_code'],
                        'purchase_type' => $params['purchase_type'],
                        'purchase_time' => strtotime($params['purchase_time']),
                        'delivery_time' => strtotime($params['delivery_time']),
                        'customers_id' => (int)$params['customers_id'],//客户
                        'sale_user' => (int)$params['sale_user'],//销售员
                        'receiving_address' => $params['receiving_address'],
                        'number' => $number,
                        'all_money' => $all_money,

                        'tax_money' => $tax_money,
                        'money_tax_price' => $money_tax_price,

                        'preferential_rate' => $params['preferential_rate'],
                        'preferential_money' => $params['preferential_money'],
                        'real_money' => $params['real_money'],
                        'note' => $params['note'],
                        'preparation_id' => $admin['id'],
                        'operation_id' => $admin['id'],
                        'updatetime' => time(),
                    ];
                }

                if ($this->model->where('shop_id', $this->shop_id)->where(['purchase_code' => trim($params['purchase_code']), 'id' => ['<>', $ids]])->find()) {
                    $this->error('单据编号已占用');
                }

                //附件记录开始
                $enclosureLog = [];
                if (isset($params['enclosure']) && !empty($params['enclosure'])) {//选择了原始单据
                    $enclosure = explode(',', $params['enclosure']);
                    $enclosurelist = Db::name('kuyou_enclosure')->where('shop_id', $this->shop_id)->where(['id' => ['in', $params['enclosure']]])->select();
                    if (sizeof($enclosurelist) != sizeof($enclosure)) {
                        $this->error('选择的原始单据有误，请重新选择');
                    } else {
                        foreach ($enclosure as $k => $v) {
                            $enclosureLog[] = [
                                'shop_id' => $this->shop_id,
                                'enclosure_id' => $v,
                                'purchase_code' => $params['purchase_code'],
                                'type' => '4',
                            ];
                        }
                    }
                    unset($params['enclosure']);
                }
                //附件记录结束

                $result = false;
                Db::startTrans();
                try {
                    if ($examine != 1 && $row['examine_status'] == 1) {
                        $this->examine($ids, 2);
                    }

                    //添加附件记录
                    Db::name('kuyou_enclosure_log')->where('shop_id', $this->shop_id)->where(['order_id' => $ids, 'type' => '4'])->delete();
                    if (!empty($enclosureLog)) {
                        foreach ($enclosureLog as $enclosureLog_k => $enclosureLog_v) {
                            $enclosureLog[$enclosureLog_k]['order_id'] = $ids;
                        }
                        Db::name('kuyou_enclosure_log')->insertAll($enclosureLog);
                    }
                    //添加附件记录结束

                    $result = $this->model->where(['id' => $ids])->update($rowdata);
                    Db::name('kuyou_goods_sales_order_info')->where('shop_id', $this->shop_id)->where(['purchase_code' => $row['purchase_code']])->delete();
                    Db::name('kuyou_goods_sales_order_info')->insertAll($data);
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($examine != 1) {
                        try {
                            $exa = $this->examine($ids, 1);
                        } catch (Exception $e) {
                        }
                        if (!isset($exa) || $exa['status'] != 1) {
                            $this->error(__('No rows were inserted'));
                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);

        $purchase_info = Db::name('kuyou_goods_sales_order_info')->where('shop_id', $this->shop_id)->where(['purchase_code' => $row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k => $purchase_info_v) {
            $purchase_info[$purchase_info_k]['unit'] = json_decode((new GoodsSales())->getUnit($purchase_info_v['goods_code']), true);
        }
        $this->view->assign("purchase_info", $purchase_info);
        $this->assignconfig("purchase_id", $row['id']);

        //查询原始单据
        $enclosure_id = Db::name('kuyou_enclosure_log')->where('shop_id', $this->shop_id)->where(['order_id' => $ids, 'type' => '4'])->column('enclosure_id');
        if (!empty($enclosure_id)) {
            $this->assign('enclosure_count', sizeof($enclosure_id));
            $enclosure_id = implode(',', $enclosure_id);
        } else {
            $enclosure_id = '';
        }
        $this->assign('enclosure_ids', $enclosure_id);

        $kuyou_customers = Db::name('kuyou_customers')->where('shop_id', $this->shop_id)->where(['id' => $row['customers_id']])->field('id,customer_name')->find();
        $this->assignconfig("kuyou_customers", $kuyou_customers);

        //审核禁止输入
        $examine_set = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
        if ($examine_set == 1 && $row['examine_status'] == 1) {
            $this->assign('exclass', 'hiddens');
        }
        $this->assignconfig("purchase_type", $row['purchase_type']);

        //审核禁止输入
        $examine_set = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
        if ($examine_set == 1 && $row['examine_status'] == 1) {
            $this->assign('exclass', 'hiddens');
        }
        $this->assignconfig("examine_status", $row['examine_status']);

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            $examine = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');

            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where('shop_id', $this->shop_id)->where($pk, 'in', $ids)->select();

            foreach ($list as $list_k => $list_v) {
                if ($list_v['examine_status'] == 1) {
                    (new \app\admin\controller\kuyou\Checkout())->checkOutTime($list_v['purchase_time']);
                }

                if ($list_v['purchase_type'] == 1) {
                    $purchase_id = Db::name('kuyou_goods_saleord')->where('shop_id', $this->shop_id)->where(['order_id' => $list_v['id']])->column('purchase_id');
                    if (!empty($purchase_id)) {
                        $this->error('不能删除已生成销货单的数据');
                    }
                } else {
                    $purchase_id = Db::name('kuyou_goods_saleexc')->where('shop_id', $this->shop_id)->where(['purchase_id' => $list_v['id'], 'type' => '1'])->column('exchange_id');
                    if (!empty($purchase_id)) {
                        $this->error('不能删除已生成退货单的数据');
                    }
                }
            }

            foreach ($list as $list_k => $list_v) {
                if ($list_v['examine_status'] == 1 && $examine == 1) {
                    $this->error('不能删除已审核的数据');
                } elseif ($list_v['examine_status'] == 1 && $examine != 1) {
                    try {
                        $this->examine($list_v['id'], 2);
                    } catch (Exception $e) {
                    }
                }
            }

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    Db::name('kuyou_goods_sales_order_info')->where('shop_id', $this->shop_id)->where(['purchase_code' => $v['purchase_code']])->delete();

                    //删除附件记录
                    Db::name('kuyou_enclosure_log')->where('shop_id', $this->shop_id)->where(['purchase_code' => $v['purchase_code'], 'type' => '4'])->delete();
                }
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    //审核/反审核
    public function examine($ids = null, $examine = 1)
    {
        $examine_set = Db::name('kuyou_sets')->where('shop_id', $this->shop_id)->where(['name' => 'examine'])->value('is_checked');
        if (empty($ids)) {
            if ($examine_set != 1) {
                return ['status' => 0, 'msg' => '系统错误'];
            }
            $this->error('请选择要操作的数据');
        }
        if ($examine == 1) {
            $list = $this->model->where('shop_id', $this->shop_id)->where(['id' => ['in', $ids], 'examine_status' => '0'])->select();
            foreach ($list as $list_k => $list_v) {
                (new \app\admin\controller\kuyou\Checkout())->checkOutTime($list_v['purchase_time']);
            }
            if (empty($list)) {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '系统错误'];
                }
                $this->error('请选择需要审核的数据');
            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where('shop_id', $this->shop_id)->where(['id' => ['in', $ids], 'examine_status' => '0'])->update(['examine_status' => 1, 'examine_id' => $admin['id'], 'examine_time' => time(), 'operation_id' => $admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (isset($result) && $result !== false) {
                if ($examine_set != 1) {
                    return ['status' => 1, 'msg' => '操作成功'];
                }
                $this->success(sizeof($list) . '条数据审核成功');
            } else {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '操作失败'];
                }
                $this->error('审核失败');
            }
        } else {
            $list = $this->model->where('shop_id', $this->shop_id)->where(['id' => ['in', $ids], 'examine_status' => '1'])->field('id,purchase_id,purchase_time')->select();
            foreach ($list as $list_k => $list_v) {
                (new \app\admin\controller\kuyou\Checkout())->checkOutTime($list_v['purchase_time']);
            }
            if (empty($list)) {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '操作失败'];
                }
                $this->error('请选择需要反审核的数据');
            }
            foreach ($list as $list_k => $list_v) {
                $purchase_id = Db::name('kuyou_goods_saleord')->where('shop_id', $this->shop_id)->where(['order_id' => $list_v['id']])->column('purchase_id');
                if (!empty($purchase_id)) {
                    if ($examine_set != 1) {
                        return ['status' => 0, 'msg' => '不能操作已生成销货单的数据'];
                    }
                    $this->error('不能反审核已生成销货单的数据');
                }
                $purchase_id = Db::name('kuyou_goods_saleexc')->where('shop_id', $this->shop_id)->where(['purchase_id' => $list_v['id'], 'type' => '1'])->column('exchange_id');
                if (!empty($purchase_id)) {
                    if ($examine_set != 1) {
                        return ['status' => 0, 'msg' => '不能操作已生成退货单的数据'];
                    }
                    $this->error('不能反审核已生成退货单的数据');
                }
            }
            $admin = Session::get('admin');
            Db::startTrans();
            try {
                $result = $this->model->where('shop_id', $this->shop_id)->where(['id' => ['in', $ids], 'examine_status' => '1'])->update(['examine_status' => 0, 'examine_id' => 0, 'examine_time' => '', 'operation_id' => $admin['id']]);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if (isset($result) && $result !== false) {
                if ($examine_set != 1) {
                    return ['status' => 1, 'msg' => '操作成功'];
                }
                $this->success(sizeof($list) . '条数据反审核成功');
            } else {
                if ($examine_set != 1) {
                    return ['status' => 0, 'msg' => '操作失败'];
                }
                $this->error('反审核失败');
            }
        }
    }

    public function checkPurchase()
    {
        $order_id = isset($_POST['order_id']) ? trim($_POST['order_id']) : 0;
        if (empty($order_id)) {
            $this->error('参数错误');
        }
        $row = Db::name('kuyou_goods_sales_order')
            ->where('shop_id', $this->shop_id)
            ->where(['id' => $order_id])
            ->field('examine_status,purchase_code')
            ->find();
        if (empty($row)) {
            $this->error('参数错误');
        }
        if ($row['examine_status'] != 1) {
            $this->error('此销货订单未审核，不可生成销货单');
        }
        $purchase_info = Db::name('kuyou_goods_sales_order_info')->where('shop_id', $this->shop_id)->where(['purchase_code' => $row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k => $purchase_info_v) {
            $purord_info = Db::name('kuyou_goods_saleord_info')->where('shop_id', $this->shop_id)->where(['order_id' => $purchase_info_v['id']])->field('sum(number) as number,sum(money) as money')->select();
            $gp_number = isset($purord_info[0]['number']) ? $purord_info[0]['number'] : 0;
            if ($purchase_info_v['number'] - $gp_number <= 0) {
                unset($purchase_info[$purchase_info_k]);
            }
        }
        if (empty($purchase_info)) {
            $this->error('此销货订单已全部生成销货单');
        }
        $this->success();
    }

    public function checkExchange()
    {
        $order_id = isset($_POST['order_id']) ? trim($_POST['order_id']) : 0;
        if (empty($order_id)) {
            $this->error('参数错误');
        }
        $row = Db::name('kuyou_goods_sales_order')
            ->where('shop_id', $this->shop_id)
            ->where(['id' => $order_id])
            ->field('examine_status,purchase_code')
            ->find();
        if (empty($row)) {
            $this->error('参数错误');
        }
        if ($row['examine_status'] != 1) {
            $this->error('此销货订单未审核，不可生成退货单');
        }
        $purchase_info = Db::name('kuyou_goods_sales_order_info')->where('shop_id', $this->shop_id)->where(['purchase_code' => $row['purchase_code']])->select();
        foreach ($purchase_info as $purchase_info_k => $purchase_info_v) {
            $purord_info = Db::name('kuyou_goods_saleexc_info')->where('shop_id', $this->shop_id)->where(['purchase_id' => $purchase_info_v['id'], 'type' => '1'])->field('sum(number) as number,sum(money) as money')->select();
            $gp_number = isset($purord_info[0]['number']) ? $purord_info[0]['number'] : 0;
            if ($purchase_info_v['number'] - $gp_number <= 0) {
                unset($purchase_info[$purchase_info_k]);
            }
        }
        if (empty($purchase_info)) {
            $this->error('此销货订单已全部生成退货单');
        }
        $this->success();
    }

}
